package com.github.binarywang.demo.wx.mp.handler;

import com.github.binarywang.demo.wx.mp.service.PushService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public abstract class SubscribeHandler extends AbstractHandler {
//    @Autowired
//    private userservice us;
    @Autowired
    private PushService pushService;
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        WxMpXmlOutMessage responseResult = null;
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
                responseResult = pushService.getMessage(userWxInfo, wxMessage, weixinService);

            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        if (responseResult!=null){
            WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
            item.setUrl("");
            item.setTitle("点我领取环保袋");
            item.setDescription("零塑生活,还地球一片蓝!\n本链接 1 次有效!");
            item.setPicUrl("https://lssh.oss-cn-shenzhen.aliyuncs.com/static/web/icon/cr.png");
            responseResult =  WxMpXmlOutMessage.NEWS()
                .addArticle(item)
                .toUser(wxMessage.getFromUser())
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
        }

        logger.info("返回的消息 {}",responseResult);
        return responseResult;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    public WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
